package com.nbsaas.boot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class CodeExecutionService {
    private static final String TEMP_DIR = "temp";
    private static final String JAVA_EXTENSION = ".java";
    private static final Pattern CLASS_NAME_PATTERN = Pattern.compile("public\\s+class\\s+(\\w+)");

    public String executeCode(String code) {
        try {
            // 创建临时目录
            Path tempDir = Paths.get(TEMP_DIR);
            if (!Files.exists(tempDir)) {
                Files.createDirectory(tempDir);
            }

            // 从代码中提取类名
            String className = extractClassName(code);
            if (className == null) {
                return "错误：未找到公共类定义";
            }

            // 使用类名作为文件名
            Path sourceFile = tempDir.resolve(className + JAVA_EXTENSION);

            // 写入源代码
            Files.write(sourceFile, code.getBytes());

            // 编译代码
            ProcessBuilder compileProcess = new ProcessBuilder("javac", sourceFile.toString());
            Process compile = compileProcess.start();
            int compileResult = compile.waitFor();

            if (compileResult != 0) {
                // 编译失败，读取错误信息
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(compile.getErrorStream()))) {
                    return "编译错误：\n" + reader.lines().reduce("", (a, b) -> a + "\n" + b);
                }
            }

            // 执行代码
            ProcessBuilder runProcess = new ProcessBuilder("java", "-cp", TEMP_DIR, className);
            Process run = runProcess.start();
            int runResult = run.waitFor();

            // 读取执行结果
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(run.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }

            // 清理临时文件
            Files.deleteIfExists(sourceFile);
            Files.deleteIfExists(tempDir.resolve(className + ".class"));

            return output.toString();
        } catch (Exception e) {
            log.error("代码执行失败", e);
            return "执行错误：" + e.getMessage();
        }
    }

    private String extractClassName(String code) {
        Matcher matcher = CLASS_NAME_PATTERN.matcher(code);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
} 